/**
 * Created by seeker910 on 2017/4/16.
 *  @description 集成了模型结构以及对象的CURD操作
 *  @memberof Rsd.data
 */
Rsd.define('Rsd.data.ModelSchema', {
    extend:'Rsd.common.Object',
    xtype:'model-schema',
    text:'',
    name:'',
    keys:[],
    /**
     * @description 新增对象Service接口
     */
    insertService:'',
    /**
     * @description 修改对象Service接口
     */
    updateService:'',
    /**
     * @description 删除对象Service接口
     */
    deleteService:'',
    /**
     * @description 查找单个对象Service接口
     */
    findService:'',
    /**
     * @description 获取列表数据Service接口
     */
    listService:'',
    /**
     * @description 上传文件Service接口
     */
    uploadService:'',
    /**
     * @description 下载Service接口
     */
    downloadService:'',
    /**
     *  @description 列表默认显示字段
     */
    //columns:[],
    /**
     *  @description 表单默认显示字段
     */
    //fields:[],
    /**
     * 
     * @param {*} searchColumns  查询列 
     */
    //searchColumns:[],
    /**
     * 
     * @param {*} sortColumns 排序列 
     */
    //sortColumns:[]
    /**
     * @constructs Rsd.data.ModelSchema
     * @classdesc Rsd.data.ModelSchema 在js环境中，进一步对模型的结构和模型的CURD service操作进行封装。
     *
     */
    constructor: function ModelSchema (config) {
        config = config || {};
        this.apply(config);
    },
    /**
    * @description 对已存在但列进行属性合并，对不存在列不会添加到原始数组中,可通过列的visible属性控制列的显示状态
    * */
    getColumns:function getColumns(cols) {


        var  _temp = [];
        var _list = cols||[];
 
        for(var i in _list)
        {
            var _c = _list[i];
            if(Rsd.isEmpty(_c.name))
            {
                continue;
            }
            if(this.__columns_m[_c.name])
            { 
                this.__columns_m[_c.name].tip = this.__columns_m[_c.name].text;
                Rsd.apply(this.__columns_m[_c.name],_c);
               
            }
            else
            {
                _temp.push(_c);
            }
        }
        //合并
        _temp = _temp.concat(this.columns||[]);

        _temp.sort(function (a,b) {
            return a.index - b.index;
        })

        var _rs = [];
        for(var i in _temp)
        {
            if(_temp[i].visible === false)
            {
                continue;
            }
            _rs.push(_temp[i])
        }

        return _rs;
    },
    /** 
    * @description 对已存在但字段进行合并，对不存在字段不会添加到原始数组中
    * */
    getFields:function getFields(fields) {

        var  _temp = [];

        var _list = fields||[];
        for(var i in _list)
        {
            var _f = _list[i];
            if(Rsd.isEmpty(_f.name))
            {
                continue;
            }
            if(this.__fields_m[_f.name])
            {
                Rsd.apply(this.__fields_m[_f.name],_f)
            }
            else
            {
                _temp.push(_f);
            }
        }
        //合并
        _temp = _temp.concat(this.fields||[]);
        _temp.sort(function (a,b) {
            return a.index - b.index;
        })

        return _temp;
    },
    /**
    * @description 获取键值
    * */
    getKeyValue:function getKeyValue(object)
    {
        if(Rsd.isEmpty(this.keys))
        {
            return null;
        }
        var obj = object || {};
        return obj[this.keys[0]];
    },
    /**
    * @description 创建初始对象，仅保留 表单字段中存在字段
    * */
    makeObject:function makeObject(object)
    {
        var _old_obj = object||{};
        var _new_obj = {};
        for(var i in this.fields)
        {
            var _p = this.fields[i].dataIndex;
            if(Rsd.isNullOrUndefined(_p))
            {

                continue;
            }
            var _type = this.fields[i].xtype;
            if(_old_obj.hasOwnProperty(_p))
            {
                _new_obj[_p]= _old_obj[_p];
            }
            else
            {
                switch (_type)
                {
                    case 'number':
                    case 'checkbox':
                        _new_obj[_p]= 0;
                        break;
                    case 'date':
                        break;
                    default:
                        _new_obj[_p]= '';
                        break;
                }

            }

        }
        for(var i in this.keys)
        {
            var _p = this.keys[i];
            if(Rsd.isNullOrUndefined(_p))
            { 
                continue;
            }

            if(_old_obj.hasOwnProperty(_p))
            {
                _new_obj[_p]= _old_obj[_p];
            }
        }
        return _new_obj;
    },
    /**
    * @description 新增对象
    *
    * */
    insertObject:function insertObject(object,callback) {
        //curd 权限检查
        var curd = this.curd;
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
        if((curd & 1) == 0)
        {
            Rsd.msg("权限限制，无法执行新增。(ERROR:00001)");
            return;
        }
        if(Rsd.isEmpty(this.insertService))
        {
            Rsd.msg("权限限制，无法执行新增。(ERROR:10001)");
            return;
        }

        if (Rsd.isString(this.insertService)) {

            var _data = this.makeObject(object);

            var _service =Rsd.app.getService(this.insertService);
            if(_service)
            {
                _service.request(_data, callback,'正在保存，请稍后...',null,{modelType: this.name});
            }
            else
            {
                Rsd.msg("服务不存在，无法执行新增。(ERROR:20001)");
            }
            
        }
    },
    /**
    * @description 修改对象
    *
    * */
    updateObject:function updateObject(object,callback) {

        var curd = this.curd;
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
        if((curd & 2) == 0)
        {
            Rsd.msg("权限限制，无法执行修改。(ERROR:00002)");
            return;
        }
        if(Rsd.isEmpty(this.updateService))
        {
            Rsd.msg("权限限制，无法执行修改。(ERROR:10002)");
            return;
        }

        if (Rsd.isString(this.updateService)) {

            var _data = object;  
            var _routeArgs = {modelType: this.name};
            _routeArgs[this.keys[0]] = _data[this.keys[0]];

            var _service = Rsd.app.getService(this.updateService); 
            if(_service)
            {
                _service.request(_data, callback,'正在保存，请稍后...',null,_routeArgs);
            }
            else
            {
                Rsd.msg("服务不存在，无法执行修改。(ERROR:20002)");
            }
            
        }
    },
    /**
    * @description 删除对象
    *
    * */
    deleteObject:function deleteObject(object,callback) {

        if(Rsd.isEmpty(this.keys))
        {
            Rsd.msg("类型：" + this.name + "主键不存在，无法删除。");
            return ;
        }
        var curd = this.curd;
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
        if((curd & 8) == 0)
        {
            Rsd.msg("权限限制，无法执行删除。(ERROR:00003)");
            return;
        } 
        if(Rsd.isEmpty(this.deleteService))
        {
            Rsd.msg("权限限制，无法执行删除。(ERROR:10003)");
            return;
        }
        //console.log(this.keys);
        var key = object[this.keys[0]];
        if (Rsd.isString(this.deleteService)) {
            var _data = {modelType: this.name,key:key};

            var _service =Rsd.app.getService(this.deleteService);
            if(_service)
            {
                _service.request(_data, callback,'正在删除，请稍后...');
            }
            else
            {
                Rsd.msg("服务不存在，无法执行删除。(ERROR:20003)");
            }
             
        }
    },
    /**
    * @description 获取单个对象
    * */
    findObject:function findObject(key,callback) {

        var curd = this.curd;
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
        if((curd & 4) == 0)
        {
            Rsd.msg("权限限制，无法执行查看。(ERROR:00004)");
            return;
        } 
        if(Rsd.isEmpty(this.findService))
        {
            Rsd.msg("权限限制，无法执行查看。(ERROR:10004)");
            return;
        }

        if(Rsd.isEmpty(this.keys))
        {
            return null;
        }

        if (Rsd.isString(this.findService)) {
            var _data = {modelType: this.name};
            _data[this.keys[0]] = key;
            var _service = Rsd.app.getService(this.findService);
            if(_service)
            {
                _service.request(_data, callback,'正在加载，请稍后...');
            }
            else
            {
                Rsd.msg("服务不存在，无法执行查看。(ERROR:20004)");
            }
        }
    },
    /**
    * @description 获取对象列表
    * */  
    listObjects:function listObjects(args,callback) {
        //debugger;
        var curd = this.curd;
        if(curd=== undefined || curd === null)
        {
            curd=15;
        }
        if((curd & 4) == 0)
        {
            Rsd.msg("权限限制，无法执行查看。(ERROR:00005)");
            return;
        } 
        if(Rsd.isEmpty(this.listService))
        {
            Rsd.msg("权限限制，无法执行查找。(ERROR:10005)");
            return;
        }
         
        var _args = args|| {}; 
        _args.modelType = this.name  
        _args.sort = _args.sort || [];
        if(_args.sort.length == 0)
        {
            //_args.sort.push({name:'CreateTime',direction:'desc'});
        }

        if(Rsd.isArray(_args.where))
        {
            for(var i in _args.where)
            {
                var _w = _args.where[i];
                if (!Rsd.isString(_w['name'])) {
                    throw new Error('Property [name] is not a effective value in where json .');
                }
                if (!Rsd.isString(_w['op'])) {
                    throw new Error('Property [op] is not a effective value in where json .');
                }
                if ((_w['op'].toLowerCase() != 'isnull' && _w['op'].toLowerCase() != 'isnotnull') && (_w['value'] == undefined || _w['value'] == null)) {
                    throw new Error('Property [value] is not a effective value in where json .');
                }
            }
        }

        var _service = Rsd.app.getService(this.listService);
        if(_service)
        {
            _service.request(_args, callback,'正在加载，请稍后...');
        }
        else
        {
            Rsd.msg("服务不存在，无法执行查找。(ERROR:20005)");
        }
    }


},function (type) {

    var _columnsGetter = function () {
       if(this.__columns == undefined)
       {
           this.__columns = [];
       }
        return this.__columns;
    };

    var _columnsSetter = function (value) {

        this.__columns = value;
        this.__columns_m ={};
        for(var i in this.__columns)
        {
            var _c = this.__columns[i];
            if(Rsd.isEmpty(_c.name))
            {
                continue;
            }
            this.__columns_m[_c.name] = _c;

        }
    }

    this.defineProperty(type,"columns", _columnsGetter, _columnsSetter,false);


    var _fieldsGetter = function () {
        if(this.__fields == undefined)
        {
            this.__fields = [];
        }
        return this.__fields;
    };

    var _fieldsSetter = function (value) {

        this.__fields = value;
        this.__fields_m = {};
        for(var i in this.__fields)
        {
            var _f = this.__fields[i];
            if(Rsd.isEmpty(_f.name))
            {
                continue;
            }
            this.__fields_m[_f.name] = _f;
        }
    }

    this.defineProperty(type,"fields", _fieldsGetter, _fieldsSetter,false);

    //searchColumns
    this.defineProperty(type,"searchColumns", function(){return Rsd.clone(this.___searchColumns||[]);}, function(value){this.___searchColumns=value;},false);
    //sortColumns
    this.defineProperty(type,"sortColumns", function(){return Rsd.clone(this.___sortColumns||[]);}, function(value){this.___sortColumns=value;},false);
});